package com.gs.m_change_password

import android.content.Context
import android.os.Handler
import android.os.Looper
import com.gs.common.BaseStateCallback
import com.gs.common.constant.StateCode

class ChangePasswordPersistent(context: Context) {

    private val changePasswordModel by lazy { ChangePasswordModel.getInstance(context) }
    private val handler = Handler(Looper.getMainLooper())

    fun changePassword(username: String, password: String, changePassword: String, callback: OnChangePasswordStateCallback) {
        Thread{
            // 查询数据耗时操作
            changePasswordModel.changePassword(username, password, changePassword) {
                when (it) {
                    StateCode.STATE_LOADING -> {
                        handler.post {
                            callback.onChangePasswordLoading()
                        }
                    }
                    StateCode.STATE_SUCCESS -> {
                        handler.post {
                            callback.onChangePasswordSuccess()
                        }
                    }
                    StateCode.STATE_FAILED -> {
                        handler.post {
                            callback.onChangePasswordFailed()
                        }
                    }
                    StateCode.NETWORK_ERROR -> {
                        handler.post {
                            callback.onNetworkError()
                        }
                    }
                    StateCode.SERVER_ERROR -> {
                        handler.post {
                            callback.onServerError()
                        }
                    }
                    StateCode.UNKNOWN_ERROR -> {
                        handler.post {
                            callback.onUnknownError()
                        }
                    }
                }
            }
        }.start()
    }

    interface OnChangePasswordStateCallback: BaseStateCallback{
        fun onChangePasswordLoading() {}
        fun onChangePasswordSuccess()
        fun onChangePasswordFailed()
    }

    companion object {
        private var instance: ChangePasswordPersistent? = null
        fun getInstance(context: Context): ChangePasswordPersistent {
            if (instance == null) {
                synchronized(this::class) {
                    if (instance == null) {
                        instance = ChangePasswordPersistent(context)
                    }
                }
            }
            return instance!!
        }
    }
}